import { useTableData } from "@/components/SmTable/src/utils";
import { mockFieldMap, mockList } from "@/utils/mock";
import { mockArr } from "./mock";
import VehicleAPI from "@/api/config/car-manage";
import { isNotMap } from "@/commonData/dict";

export const useTable = () => {
  const list: any = ref([]);
  const total = ref(0);
  const loading = ref(false);

  const { tableOptions, transformTableOptions } = useTableData();

  const fieldMap = {
    ownerCertTypeText: "车主证件类型",
    vehicleCategoryName: "车辆种类",
    vehicleNatureName: "车辆性质",
    vehiclePlateTypeName: "号牌种类",
    vin: "车架号",

    ownerGenderText: "性别",
    ownerEthnicity: "民族",

    approvedCapacity: "核定人数",
    approvedLoad: "核定载客/质量",
    avgMileage: "平均行驶里程 (公里)",
    claimCount: "历史出险次数",
    curbWeight: "整备质量 (kg)",
    customerNameText: "所属客户",
    displacement: "排量 (L)",
    engineNo: "发动机号码",
    firstRegDate: "初登日期",
    isImported: {
      label: "是否进口",
      slot: "isImported",
      textMap: isNotMap,
    },

    ownerAddress: "所在地址",
    ownerBirthday: "出生日期",
    ownerCertExpiryDate: "证件有效期截止日期",
    ownerCertNumber: "证件号码",

    ownerName: "车主姓名",
    plateNo: "车牌号",
    power: "功率 (KW)",
    purchasePrice: "车辆价格",
    ratedPayload: "额定载质量(kg)",
    totalWeight: "总质量(kg)",

    createdAt: "创建时间",
    updatedAt: "更新时间",
    operate: {
      label: "操作",
      slot: "operate",
      fixed: "right",
      width: "180px",
    },
  };

  // const fieldMap = mockFieldMap(mockArr);

  tableOptions.value = transformTableOptions(fieldMap);

  // // 先模拟数据
  // const getList = async () => {
  //   const data = mockList(mockArr);
  //   list.value = data.list;
  //   total.value = data.total;
  // };

  const queryParams: any = reactive({
    pageNum: 1,
    pageSize: 10,
  });

  /** 查询列表 */
  const getList = async () => {
    loading.value = true;
    try {
      const data = await VehicleAPI.getPage(queryParams);
      list.value = data.list;
      total.value = data.total;
    } finally {
      loading.value = false;
    }
  };

  function handleQuery() {
    queryParams.pageNum = 1;
    getList();
  }

  const queryFormRef = ref();
  /** 添加/修改操作 */
  const formRef = ref();
  const openForm = (type: string, id?: number) => {
    formRef.value.open(type, id);
  };

  /** 重置按钮操作 */
  const handleResetQuery = () => {
    queryFormRef.value.resetFields();
    nextTick(() => {
      handleQuery();
    });
  };

  return {
    tableOptions,
    list,
    total,
    loading,
    queryParams,
    getList,
    handleQuery,
    handleResetQuery,
    queryFormRef,
    formRef,
    openForm,
  };
};
